import React, { Component } from 'react';
import { Animated, TextInput, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter, Platform } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { width, unitWidth, statusBarHeight, titleHeight } from '../constants/AdapterUtil';
import Swiper from 'react-native-swiper';
import StickyListView from '../components/StickyListView';
import MoreClassification from '../components/MoreClassification';
import { DeleteTextView } from '../components/MyTextView';
import { FindTypeModal, FindTimeModal, FindPayTypeModal, FindAreaModal } from '../components/Modal';
import Permissions from 'react-native-permissions';
import CommonUtil from '../constants/CommonUtil';
import { api_order_workorder_oneCate, api_order_workorder_workorderList } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import { CenterComponent } from '../components/MyHeader';
import { SubmitButton5, SubmitButton6, SubmitButton7 } from '../components/Button';
import { show } from '../constants/Toast';
import FastImage from 'react-native-fast-image';

export default class FindScreen extends Component {
    static navigationOptions = ({ navigation, jumpToIndex, scene }) => ({
        title: 'home',
        tabBarLabel: ({ focused }) => (
            <TabBarTitle
                focused={focused}
                title={'找工单'}
            />
        ),
        tabBarIcon: ({ focused }) => (
            <TabBarAnimationImage
                focused={focused}
                hasSelect={require('../res/ic_find_c.png')}
                noSelect={require('../res/ic_find_n.png')}
            />
        ),
        tabBarOnPress: (options) => {
            if (global.userInfo.user_type == '1') {
                show('只有公司账户才能找工单')
                return
            } else {
                DeviceEventEmitter.emit('tabClick', '');
                options.defaultHandler();
            }
        },
        tabBarOnLongPress: (options) => {
            return
        },
    });

    constructor(props) {
        super(props)
        this.state = {
            pubdate: 0,
            pay_type: 0,
            area: '',
            list: [],

            oneCate: [],//一个分类
            chooseCate: {},
            desc: '1',//1关闭发布框,2打开时间发布框,3打开平台交易框,4打开地区框，5打开筛选框
        }
    }

    componentDidMount() {
        this.getData(1);
        this.props.navigation.addListener('didFocus', payload => {
            this.getOneCate();
        })
    }

    componentWillUnmount() {

    }


    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF5 }}>
                <StatusBar
                    animated={false} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式：backgroundColor, barStyle和hidden
                    hidden={false}  //是否隐藏状态栏。
                    translucent={true}//指定状态栏是否透明。设置为true时，应用会在状态栏之下绘制（即所谓“沉浸式”——被状态栏遮住一部分）。常和带有半透明背景色的状态栏搭配使用。
                    barStyle={'dark-content'} // enum('default', 'light-content', 'dark-content')
                    backgroundColor={'rgba(0,0,0,0)'}
                />
                <View style={{ height: statusBarHeight + titleHeight, width: width, backgroundColor: Colors.white }}>
                    <View style={{ marginTop: statusBarHeight, height: titleHeight, width: width, backgroundColor: Colors.white, flexDirection: 'row', borderWidth: 0.5, borderBottomColor: Colors.colorE8, borderColor: Colors.transparent }}>
                        <View style={{ flex: 1, marginLeft: 16 * unitWidth, flexDirection: 'row', alignItems: 'center' }} >
                            <TouchableOpacity style={{ width: 75 * unitWidth, height: 25 * unitWidth, borderRadius: 20, backgroundColor: Colors.colorEF, flexDirection: 'row', alignItems: 'center', }}
                                onPress={() => {
                                    this.props.navigation.navigate('SearchOrder')
                                }}>
                                <Image source={require('../res/ic_search.png')}
                                    style={{ width: 13 * unitWidth, height: 14 * unitWidth, marginHorizontal: 10 * unitWidth }}
                                    resizeMode='stretch' />
                                <Text style={{ fontSize: 10 * unitWidth }}>搜索</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{ flex: 5, alignItems: 'center', justifyContent: 'center' }}>
                            <CenterComponent title='找工单' fontColor={Colors.black} />
                        </View>
                        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>

                        </View>
                    </View>
                </View>
                <View style={{ flex: 1 }}>
                    <StickyListView
                        ref='StickyListView'
                        list={this.state.list}
                        showTopBtn={true}
                        scrollEnabled={this.state.desc == '1'}
                        getList={this.getData.bind(this)}
                        stickView={
                            <View style={{ height: 68 * unitWidth, backgroundColor: Colors.white, width: width }}>
                                <View style={{ flexDirection: 'row', height: 31 * unitWidth, alignItems: 'center' }}>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc != '1' && this.state.desc == '2' ? '1' : '2'
                                            }, () => {
                                                this.hideAllModal();
                                                if (this.state.desc == '2') {
                                                    this.refs.FindTimeModal.showModal();
                                                }
                                            })
                                        }}>
                                        <Text style={{ color: Colors.black }}>发布时间</Text>
                                        <Image source={this.state.desc != '2' ? require('../res/ic_arrow_2.png') : require('../res/zgd_xqxqxl.png')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc != '1' && this.state.desc == '3' ? '1' : '3'
                                            }, () => {
                                                this.hideAllModal();
                                                if (this.state.desc == '3') {
                                                    this.refs.FindPayTypeModal.showModal();
                                                }
                                            })
                                        }}>
                                        <Text style={{ color: Colors.black }}>平台交易</Text>
                                        <Image source={this.state.desc != '3' ? require('../res/ic_arrow_2.png') : require('../res/zgd_xqxqxl.png')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc != '1' && this.state.desc == '4' ? '1' : '4'
                                            }, () => {
                                                this.hideAllModal();
                                                if (this.state.desc == '4') {
                                                    this.refs.FindAreaModal.showModal();
                                                }
                                            })
                                        }}>
                                        <Text style={{ color: Colors.black }}>地区</Text>
                                        <Image source={this.state.desc != '4' ? require('../res/ic_arrow_2.png') : require('../res/zgd_xqxqxl.png')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc != '1' && this.state.desc == '5' ? '1' : '5'
                                            }, () => {
                                                this.hideAllModal();
                                                if (this.state.desc == '5') {
                                                    this.refs.FindTypeModal.showModal();
                                                }
                                            })
                                        }}>
                                        <Image source={this.state.desc == '5' ? require('../res/ic_sx_o.png') : require('../res/ic_sx.png')}
                                            style={{ width: 13 * unitWidth, height: 13 * unitWidth }}
                                            resizeMode='stretch' />
                                        <Text style={{ marginLeft: 3 * unitWidth }}>筛选</Text>
                                    </TouchableOpacity>
                                </View>
                                <View style={{ flexDirection: 'row', height: 37 * unitWidth, alignItems: 'center', flexWrap: 'wrap' }}>
                                    {this.getScreenView()}
                                </View>
                            </View>
                        }
                        top={0}
                        stickHeight={68 * unitWidth}
                        scrollStick={0.1}
                        childView={(item, index) => {
                            return (
                                <View style={{ justifyContent: 'center', alignItems: 'center', width: width, height: 161 * unitWidth }}>
                                    <TouchableOpacity style={{
                                        width: width,
                                        height: 161 * unitWidth,
                                        backgroundColor: Colors.white, justifyContent: 'center'
                                    }} activeOpacity={0.7}
                                        onPress={() => {
                                            this.props.navigation.navigate('DemandDetail', { id: item.id, showOffer: 1 })
                                        }}>
                                        <View style={{
                                            paddingHorizontal: 20 * unitWidth,
                                            flexDirection: 'row', alignItems: 'center'
                                        }}>
                                            <FastImage style={{ width: 115 * unitWidth, height: 90 * unitWidth }} source={{ uri: item.picture }} resizeMode={FastImage.resizeMode.cover} />
                                            <View style={{ alignItems: 'flex-start', marginLeft: 7 * unitWidth }}>
                                                <Text style={{ color: Colors.black, fontSize: 15 }}>{item.title}</Text>
                                                <Text style={{ color: Colors.color99, fontSize: 13, marginTop: 7 * unitWidth }}>加工数目：{item.total_count}</Text>
                                                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 7 * unitWidth }}>
                                                    <Image style={{ width: 13 * unitWidth, height: 16 * unitWidth }} source={require('../res/syss_dddw.png')} resizeMode='stretch' />
                                                    <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>地区：{item.province + '   ' + item.city}</Text>
                                                </View>
                                                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 7 * unitWidth }}>
                                                    <Image style={{ width: 14 * unitWidth, height: 14 * unitWidth }} source={require('../res/fws_clsj.png')} resizeMode='stretch' />
                                                    <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>截止报价日期：</Text>
                                                    <Text style={{ color: Colors.colorOrange, fontSize: 13, marginLeft: 5 * unitWidth }}>{item.end_date}</Text>
                                                </View>
                                            </View>
                                            <View style={{ alignSelf: 'flex-start', alignItems: 'center', position: 'absolute', right: 15 * unitWidth }}>
                                                <Text style={{ color: Colors.color66, fontSize: 13, marginTop: 10 * unitWidth }}>{item.createtime}发布</Text>
                                            </View>
                                        </View>
                                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 15 * unitWidth, justifyContent: 'space-between', marginHorizontal: 15 * unitWidth }}>
                                            <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>
                                                已报价服务商
                                            <Text style={{ color: Colors.colorOrange }}>   {item.quoted_price_count}家</Text>
                                            </Text>
                                            <SubmitButton7 style={{ marginLeft: 5 * unitWidth }} text='立即报价' onPress={() => {
                                                this.props.navigation.navigate('Quote', { id: item.id })
                                            }} />
                                        </View>
                                        {index == this.state.list.length - 1 ?
                                            null : <View style={{ backgroundColor: Colors.colorE8, width: 338 * unitWidth, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                                        }
                                    </TouchableOpacity>
                                </View>
                            )
                        }}
                        coverListView={
                            this.state.desc != '1' ?
                                <TouchableOpacity style={{
                                    position: 'absolute',
                                    top: 68 * unitWidth,
                                    height: '100%', width: '100%', backgroundColor: 'rgba(0,0,0,0.3)'
                                }} activeOpacity={1}
                                    onPress={() => {
                                        this.setState({
                                            desc: '1'
                                        }, () => {
                                            this.hideAllModal();
                                        })
                                    }} /> : <View />
                        } />
                    <FindTypeModal ref='FindTypeModal' cate={this.state.oneCate} onChoose={(item, type) => {
                        // if (type == '3') {
                        //     this.setState({
                        //         desc: '1',
                        //     })
                        // }
                        this.setState({
                            desc: '1',
                            chooseCate: item
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                        })
                    }} />
                    <FindTimeModal ref='FindTimeModal' onChoose={(choose) => {
                        this.setState({
                            pubdate: choose,
                            desc: '1',
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                        })
                    }}
                    />
                    <FindPayTypeModal ref='FindPayTypeModal' onChoose={(choose) => {
                        this.setState({
                            pay_type: choose,
                            desc: '1',
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                        })
                    }}
                    />
                    <FindAreaModal ref='FindAreaModal' cate={this.state.oneCate} onChoose={(item) => {
                        this.setState({
                            area: item.name,
                            desc: '1',
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                        })
                    }} />
                </View>
            </View>
        )
    }

    hideAllModal() {
        this.refs.FindTypeModal.hideModal();
        this.refs.FindTimeModal.hideModal();
        this.refs.FindPayTypeModal.hideModal();
        this.refs.FindAreaModal.hideModal();
    }

    getCarouselView() {
        let views = []
        for (let i = 0, len = this.state.CarouselList.length; i < len; i++) {
            let item = this.state.CarouselList[i];
            views.push(
                <TouchableOpacity key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                }} activeOpacity={0.8} onPress={() => {

                }}>
                    <Image
                        source={{ uri: item }}
                        style={{
                            width: width, height: 174 * unitWidth,
                        }}
                        resizeMode='cover' />
                </TouchableOpacity>
            )
        }
        return views;
    }

    getScreenView() {
        let views = []
        for (let i = 0, len = this.state.oneCate.length; i < len && i < 4; i++) {
            let item = this.state.oneCate[i];
            views.push(
                <TouchableOpacity key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: this.state.chooseCate.id == item.id ? Colors.colorOrange : Colors.coloree,
                    borderRadius: 20,
                    paddingHorizontal: 7 * unitWidth,
                    marginHorizontal: 7 * unitWidth
                }} activeOpacity={0.5} onPress={() => {
                    if (this.state.chooseCate.id == item.id) {
                        this.setState({
                            chooseCate: {}
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                            DeviceEventEmitter.emit('FineChange', {});
                        })
                    } else {
                        this.setState({
                            chooseCate: item,
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                            DeviceEventEmitter.emit('FineChange', item);
                        })
                    }
                }}>
                    <Text style={{
                        color: this.state.chooseCate.id == item.id ? Colors.white : Colors.color99,
                    }}>{item.name}</Text>
                </TouchableOpacity>
            )
        }
        return views;
    }

    //获取一级类目
    getOneCate() {
        let params = {

        }
        postFetch(api_order_workorder_oneCate, params, {
            success: (response) => {
                this.setState({
                    oneCate: response.result
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取工单信息
    getData(page) {
        let params = {
            page: page,
            status: 2
        }
        if (this.state.chooseCate && this.state.chooseCate.id) {
            params['one_cate'] = this.state.chooseCate.id
        }
        if (this.state.pubdate && this.state.pubdate != 0) {
            params['pubdate'] = this.state.pubdate
        }
        if (this.state.pay_type && this.state.pay_type != 0) {
            params['pay_type'] = this.state.pay_type
        }
        if (this.state.area && this.state.area != '' && this.state.area != '不限') {
            params['area'] = this.state.area
        }
        postFetch(api_order_workorder_workorderList, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                    }, () => {
                        this.refs.StickyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.StickyListView.onHasMore();
                        })
                    } else {
                        this.refs.StickyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}